//
//  ZYCScheduleViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/8/10.
//

#import "ZYCScheduleViewController.h"
#import <FSCalendar.h>
#import "ZYCScheduleRootCell.h"
#import "ZYCScheduleParentCell.h"
#import "ZYCUserLoginModel.h"
#import "ZYCScheduleModel.h"
#import "ZYCScheduleRootSectionHeaderView.h"
#import "ZYCNoDataView.h"
#import "LunarFormatter.h"
#import "ZYCCalendarCell.h"


@interface ZYCScheduleViewController ()<UINavigationControllerDelegate,FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
{
    void * _KVOContext;
}
@property (nonatomic, strong) UIImageView *calendaerImgView;
@property (nonatomic, strong) FSCalendar *calendar;
@property (nonatomic, strong) LunarFormatter *lunarFormatter;
@property (nonatomic, strong) UIButton *previousButton;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) NSCalendar *gregorian;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;
@property (nonatomic, strong) UIPanGestureRecognizer *scopeGesture;
@property (nonatomic, strong) MASConstraint *calenderHeightConstraint;
@property (nonatomic, copy) NSString *userId;
@property (nonatomic, copy) NSString *userType;
@property (nonatomic, copy) NSString *courseMonth;
@property (nonatomic, strong) NSMutableArray *dataSource;
// 授课时间
@property (nonatomic, copy) NSString *courseTime;
// 日程日历数组
@property (nonatomic, strong) NSMutableArray *calendarArray;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) ZYCNoDataView *noDataView;
@end

@implementation ZYCScheduleViewController


#pragma mark - Life Cycile
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupGradientlayer];
    self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    self.lunarFormatter = [[LunarFormatter alloc] init];
    [self setupContaints];
    [self addPanGestureRecognizer];
    // 监听KVO
    [self.calendar addObserver:self forKeyPath:@"scope" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:_KVOContext];
    ZYCUserLoginModel *userLogin = [ZYCUserLoginModel userLogin];
    self.userId = userLogin.userId;
    NSInteger roleType =  [[NSUserDefaults standardUserDefaults] integerForKey:@"kUserRoleType"];
      if (roleType == 0) {
          self.userType = @"1";//教师
      }else{
          self.userType = @"2";//家长
      }
    self.courseMonth = [self getCurrentTime];

}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
    // 获取日历数据
    [self loadScheduleCalendarData];
    // 获取列表
    [self loadScheduleList];
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if (context == _KVOContext) {
//        FSCalendarScope oldScope = [change[NSKeyValueChangeOldKey] unsignedIntegerValue];
//        FSCalendarScope newScope = [change[NSKeyValueChangeNewKey] unsignedIntegerValue];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - FSCalendarDataSource && FSCalendarDelegateAppearance

- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated
{
    [self.calenderHeightConstraint uninstall];
    [self.calendar mas_updateConstraints:^(MASConstraintMaker *make) {
        self.calenderHeightConstraint = make.height.mas_equalTo(CGRectGetHeight(bounds));
    }];
}
- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date{
    return  [self.gregorian isDateInToday:date] ? @"今" :nil;
}

- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date{
    return [self.lunarFormatter stringFromDate:date];
}

- (FSCalendarCell *)calendar:(FSCalendar *)calendar cellForDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    ZYCCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:@"cell" forDate:date atMonthPosition:monthPosition];
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([self.calendarArray containsObject:dateString]) {
        cell.statusLabel.textColor = HEX_RGB(@"#41B166");
        cell.statusLabel.text = @"授课";
        return cell;
    }
    return nil;
}

- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([self.calendarArray containsObject:dateString]) {
        return 1;
    }else{
        return 0;
    }
}

// 切换月份
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    NSString *dateString = [self.dateFormatter stringFromDate:calendar.currentPage];
    self.courseMonth = dateString;
    [self loadScheduleList];
}

// 切换日期
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    NSLog(@"did select date: %@",[self.dateFormatter stringFromDate:date]);
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    self.courseMonth = dateString;
    [self loadScheduleList];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.userType isEqualToString:@"1"]) {
        ZYCScheduleRootCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCScheduleRootCell class]) forIndexPath:indexPath];
        cell.sModel = self.dataSource[indexPath.section];
        [cell setSectionCircularTableView:tableView withIndexPath:indexPath];
        return cell;
    }else{
        ZYCScheduleParentCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCScheduleParentCell class]) forIndexPath:indexPath];
        cell.model = self.dataSource[indexPath.section];
        [cell setSectionCircularTableView:tableView withIndexPath:indexPath];
        return cell;
    }
    

}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 37.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.userType isEqualToString:@"1"]) {
        return 76.0f;;
    }else{
        return 132.0f;
    }
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ZYCScheduleRootSectionHeaderView *headerView = [[ZYCScheduleRootSectionHeaderView alloc] init];
    headerView.isShowDetail = NO;
    ZYCScheduleModel *sModel = self.dataSource[section];
    headerView.sModel = sModel;
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}


#pragma mark - 网络请求
//日程日期
- (void)loadScheduleCalendarData{
    NSDictionary *params = @{
        @"userId":self.userId,
        @"userType":self.userType,
        @"courseMonth":self.courseMonth
    };
    [[URLManager sharedURLManager] postUrlString:Schedule_Post_ScheduleTime requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array = responseObject[@"body"];
                [self.calendarArray removeAllObjects];
                [self.calendarArray addObjectsFromArray:array];
                [self.calendar reloadData];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}
// 日程列表

- (void)loadScheduleList{
    NSDictionary *params = @{
        @"userId":self.userId,
        @"userType":self.userType,
        @"courseTime":self.courseMonth
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Schedule_Post_AppSchedule requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            [self.dataSource removeAllObjects];
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *dutyRecordArr = [NSArray yy_modelArrayWithClass:[ZYCScheduleModel class] json:responseObject[@"body"][@"busDutyplansRecordList"]];
                NSArray *teaScheuleArr = [NSArray yy_modelArrayWithClass:[ZYCScheduleModel class] json:responseObject[@"body"][@"busTcScheduleManageList"]];
                NSArray *parentScheuleArr = [NSArray yy_modelArrayWithClass:[ZYCScheduleModel class] json:responseObject[@"body"][@"busTcClassPlanList"]];
        
                if ([self.userType isEqualToString:@"1"]) {//教师
                    [self.dataSource addObjectsFromArray:dutyRecordArr];
                    [self.dataSource addObjectsFromArray:teaScheuleArr];
                }else{
                    [self.dataSource addObjectsFromArray:parentScheuleArr];
                }
                if (self.dataSource.count == 0) {
                    self.noDataView.hidden = NO;
                    self.tableView.hidden = YES;
                }else{
                    self.noDataView.hidden = YES;
                    self.tableView.hidden = NO;
                }
                [self.tableView reloadData];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}
#pragma mark - private method
- (void)setupContaints{
    [self.view addSubview:self.calendaerImgView];
    [self.view addSubview:self.calendar];
    [self.calendar addSubview:self.previousButton];
    [self.calendar addSubview:self.nextButton];
    [self.view addSubview:self.tableView];

    [self.calendaerImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(42.0f);
        make.height.mas_equalTo(27.0f);
    }];
    
    [self.previousButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.calendar).offset(95.0f);
        make.centerY.equalTo(self.calendar.mas_top).offset(27.0f);
        make.size.mas_equalTo(CGSizeMake(10, 8.5));
    }];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.calendar).offset(-95.0f);
        make.centerY.equalTo(self.calendar.mas_top).offset(27.0f);
        make.size.mas_equalTo(CGSizeMake(10, 8.5));
    }];
    [self.calendar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10.0f);
        make.right.equalTo(self.view).offset(-10.0f);
        make.top.equalTo(self.calendaerImgView.mas_centerY);
        self.calenderHeightConstraint = make.height.mas_equalTo(282);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.calendar.mas_bottom).offset(10.0f);
    }];
    
}

- (NSString *)getCurrentTime {
    NSString *dateTime = [self.dateFormatter stringFromDate:[NSDate date]];
    return dateTime;
}

- (void)addPanGestureRecognizer{
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.calendar action:@selector(handleScopeGesture:)];
    panGesture.delegate = self;
    panGesture.minimumNumberOfTouches = 1;
    panGesture.maximumNumberOfTouches = 2;
    [self.view addGestureRecognizer:panGesture];
    self.scopeGesture = panGesture;
    // While the scope gesture begin, the pan gesture of tableView should cancel.
    [self.tableView.panGestureRecognizer requireGestureRecognizerToFail:panGesture];
}


#pragma mark - getters

- (NSMutableArray *)calendarArray {
    if (!_calendarArray) {
        _calendarArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _calendarArray;
}

- (UIImageView *)calendaerImgView {
    if (!_calendaerImgView) {
        _calendaerImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rili"]];
    }
    return _calendaerImgView;
}

- (FSCalendar *)calendar {
    if (!_calendar) {
        _calendar = [[FSCalendar alloc] init];
        _calendar.delegate = self;
        _calendar.dataSource = self;
        _calendar.headerHeight = 50.0f;
        _calendar.appearance.headerMinimumDissolvedAlpha = 0;
        _calendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        _calendar.backgroundColor = [UIColor whiteColor];
        _calendar.placeholderType = FSCalendarPlaceholderTypeNone; //只显示当前月份
        _calendar.appearance.headerDateFormat = @"yyyy年MM月";// 设置头部时间格式
        _calendar.appearance.weekdayTextColor = HEX_RGB(@"#62676A");//设置周字体颜色
        _calendar.appearance.headerTitleColor = HEX_RGB(@"#262A28");//设置头字体颜色
        _calendar.appearance.caseOptions = FSCalendarCaseOptionsHeaderUsesUpperCase|FSCalendarCaseOptionsWeekdayUsesSingleUpperCase;
        //        _calendar.appearance.eventDefaultColor = HEX_RGB(@"#CECECE");// 设置日期下的小点点颜色
        _calendar.appearance.selectionColor = FSCalendarStandardTodayColor; // 设置点击某日某日的颜色
        _calendar.appearance.todayColor = FSCalendarStandardTodayColor;// 设置今天颜色
        [_calendar registerClass:[ZYCCalendarCell class] forCellReuseIdentifier:@"cell"];
        _calendar.allowsMultipleSelection = NO;
    }
    return _calendar;
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCScheduleRootCell class] forCellReuseIdentifier:NSStringFromClass([ZYCScheduleRootCell class])];
        [_tableView registerClass:[ZYCScheduleParentCell class] forCellReuseIdentifier:NSStringFromClass([ZYCScheduleParentCell class])];
    }
    return _tableView;
}

- (UIButton *)previousButton {
    if (!_previousButton) {
        _previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_previousButton setImage:[UIImage imageNamed:@"zuo"] forState:UIControlStateNormal];
        [_previousButton addTarget:self action:@selector(previousClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _previousButton;
}

- (UIButton *)nextButton {
    if (!_nextButton) {
        _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextButton setImage:[UIImage imageNamed:@"you"] forState:UIControlStateNormal];
        [_nextButton addTarget:self action:@selector(nextClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextButton;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}

#pragma mark - 点击事件
-(void)previousClicked:(UIButton *)sender{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:previousMonth animated:YES];
}

-(void)nextClicked:(UIButton *)sender{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:nextMonth animated:YES];
}

#pragma mark - UINavigationControllerDelegate
-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:[viewController isKindOfClass:[self class]] animated:YES];
}


#pragma mark - private method
//设置渐变
- (void)setupGradientlayer{
    //初始化CAGradientlayer对象，使它的大小为UIView的大小
    self.gradientLayer = [CAGradientLayer layer];
    self.gradientLayer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kTabBarHeight);
    
    //将CAGradientlayer对象添加在我们要设置背景色的视图的layer层
    [self.view.layer addSublayer:self.gradientLayer];
    
    //设置渐变区域的起始和终止位置（范围为0-1）
    self.gradientLayer.startPoint = CGPointMake(0, 0);
    self.gradientLayer.endPoint = CGPointMake(1, 1);
    
    //设置颜色数组
    self.gradientLayer.colors = @[(__bridge id)HEX_RGB(kBgGreenColor).CGColor,
                                  (__bridge id)HEX_RGB(kBgLightGrayColor).CGColor];
    
    //设置颜色分割点（范围：0-1）
    self.gradientLayer.locations = @[@(0.0f), @(1.0f)];
    
}

#pragma mark - UIGestureRecognizerDelegate

// Whether scope gesture should begin
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    BOOL shouldBegin = self.tableView.contentOffset.y <= -self.tableView.contentInset.top;
    if (shouldBegin) {
        CGPoint velocity = [self.scopeGesture velocityInView:self.view];
        switch (self.calendar.scope) {
            case FSCalendarScopeMonth:
                return velocity.y < 0;
            case FSCalendarScopeWeek:
                return velocity.y > 0;
        }
    }
    return shouldBegin;
}

- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

- (ZYCNoDataView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[ZYCNoDataView alloc] initWithFrame:self.tableView.frame];
        _noDataView.hidden = YES;
        [self.view addSubview:_noDataView];
    }
    return _noDataView;
}


- (void)dealloc{
//    [self.calendar removeObserver:self forKeyPath:@"scope" context:_KVOContext];
    self.navigationController.delegate = nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
